package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.common.constant.SystemConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.customer.contest.UserContent;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.redisson.RedissonBloomFilter;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private WxMaService wxMaService;

    @Resource
    private RedissonClient redissonClient;
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    /**
     * 微信登录
     *
     * @param code 微信验证码
     * @return 用户id
     */
    @Override
    public  Long login(String code) {
        //1.调用微信服务获取openId
        String openId;
        try {

            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
             openId = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            //布隆过滤器判断是否登录成功

            throw new RuntimeException(e);
        }
        //查询数据库是否有当前用户id信息
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getWxOpenId,openId);
        CustomerInfo customerInfo = this.getOne(queryWrapper);
        if (customerInfo == null) {
            //新用户添加到数据库中 
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl(UserContent.USERAVR);
            customerInfo.setWxOpenId(openId);
            customerInfoMapper.insert(customerInfo);
        }
        AuthContextHolder.setUserId(customerInfo.getId());
        return customerInfo.getId();
    }

    /**
     * 查询用户登录信息
     *
     * @param userId
     * @return
     */
    @Override
    public CustomerLoginVo getLoginVo(Long userId) {
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getId,userId).eq(CustomerInfo::getIsDeleted, SystemConstant.NOT_DELETE);
        CustomerInfo customerInfo = getOne(queryWrapper);
        if (!Optional.ofNullable(customerInfo).isPresent()) {
            throw new GuiguException(ResultCodeEnum.NOT_FOUND);
        }
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);
        customerLoginVo.setIsBindPhone(StringUtils.hasText(customerInfo.getPhone()));
        return customerLoginVo;
    }

    /**
     * 根据用户id和微信code获取微信手机号并更新
     *
     * @param updateWxPhoneForm
     */
    @Override
    public void updateWxPhoneByCode(UpdateWxPhoneForm updateWxPhoneForm) {
        String phone = "18113568959";
  /*      try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.
                    getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode()); //调用微信接口获取微信手机号
            phone =  phoneNoInfo.getPhoneNumber();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }*/
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(updateWxPhoneForm.getCustomerId());
        customerInfo.setPhone(phone);
        //更新手机号
        updateById(customerInfo);

    }

}
